from . import news_blue
from info import models, constants, db
from flask import render_template, g, request, jsonify,current_app
from info.utils.common import check_islogin
from info.utils.response_code import *
from sqlalchemy import and_



@news_blue.route('/<int:news_id>')
@check_islogin
def news_detail(news_id):

    user = g.user

    # 查询首页右边的热门排行新闻数据
    news = models.News.query.order_by(models.News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)



    news_list = []

    for new_model in news:
        news_list.append(new_model.to_dict())

    # 根据新闻id获取到详情页面的数据
    news_content = models.News.query.get(news_id)

    # 当前新闻是否被收藏,一般默认情况下,第一次进来默认值肯定是false
    is_collection = False
    # 如果user有值,说明用户已经登陆
    if user:
        # 判断当前新闻,是否在当前用户的新闻收藏列表里面
        if news_content in user.collection_news:
            is_collection = True


    # 获取到新闻的评论列表
    comments = models.Comment.query.filter(models.Comment.news_id == news_id).order_by(models.Comment.create_time.desc()).all()
    # 所有的点赞数据
    comment_likes = []
    # 所有的点赞id
    comment_likes_ids = []
    if user:
        comment_likes = models.CommentLike.query.filter(models.CommentLike.user_id == user.id).all()
        comment_likes_ids =  [comment_like.comment_id for comment_like in comment_likes]

    comments_list = []

    for comment in comments:
        comment_dict = comment.to_dict()
        if comment.id in comment_likes_ids:
            comment_dict['is_like'] = True
        comments_list.append(comment_dict)

    # 判断用户是否关注
    is_followed = False

    # 当前新闻必须有作者,才能关注, 用户必须登陆,才能关注作者

    if user:
        # 判断当前新闻的作者是否在我关注的人的列表里面(张三,李四)
        if news_content.user in user.followed:
            is_followed = True


    data = {
        "user_info": user.to_dict() if user else None,
        "click_news_list": news_list,
        "news":news_content.to_dict(),
        "is_collected":is_collection,
        "comments":comments_list,
        "is_followed": is_followed
    }
    return render_template('news/detail.html',data = data)

# # 显示新闻详细页面
# @news_blue.route("/<int:news_id>")
# @check_islogin
# def new_blue(news_id):
#
#     # 　获取点击排行榜
#     data_news_list = []
#     news = models.News.query.order_by(models.News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
#     news_list = [x.to_dict() for x in news]
#     data_news_list.append(news_list)
#
#     # 获取新闻具体信息
#     data_news = []
#     news_info = models.News.query.get_or_404(news_id)
#     data_news.append(news_info.to_dict())
#     # 点击加1
#     news_info.clicks += 1
#     db.session.commit()
#
#
#     # 获取评论
#     data_data_news_list = []
#     comments = models.Comment.query.filter(models.Comment.news_id == news_info.id).order_by(models.Comment.create_time.desc()).all()
#     comments_list = [comment.to_dict() for comment in comments]
#     # 获取评论数
#     count = len(comments_list)
#     counts = count
#     data_data_news_list.append(comments_list)
#
#     # 判断用户是否登录
#
#     user = g.user
#     isLogin = False
#     user_info = None
#     if user:
#         isLogin = True
#         user_info = user
#
#         # 判断当前用户是否收藏当前新闻
#         is_Collected = False
#         if news_info in user.collection_news:
#             is_Collected = True
#
#         #　获取当前用户所有的点赞数
#         cur_comment_likes = models.CommentLike.query.filter(models.CommentLike.user_id == user.id).all()
#         cur_comment_like_id = [cur_comment.comment_id for cur_comment in cur_comment_likes]
#
#     for comment in comments:
#         comment_dict = comment.to_dict()
#         if comment.id in cur_comment_like_id:
#             comment_dict["is_like"] = True
#
#     data = {
#         # 是否登录
#         "isLogin": isLogin,
#         # 当前用户信息
#         "user_info": user_info,
#         # 点击排行榜
#         "news_list": data_news_list,
#         # 当前新闻信息
#         "news": data_news,
#         # 是否被收藏
#         "is_collected": is_Collected,
#         # 评论列表
#         "comments": data_data_news_list,
#         # 评论数
#         "count": counts,
#         # 当前用户的点赞数
#         "cur_comment_like": None,
#
#     }
#
#
#
#
#
#
#
#
#
#
#     return render_template("news/detail.html", data=data)


# 收藏与取消收藏
@news_blue.route("/news_collect", methods=["POST"])
@check_islogin
def news_collect():
    # 获取浏览器发送来的数据
    news_id = request.json.get("news_id")
    action = request.json.get("action")  # 指定两个值：'collect', 'cancel_collect'
    # 判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map.get(RET.SESSIONERR))
    # 判断是否收到浏览器信息
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))
    # 判断action是否在范围内
    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))
    # 判断收到浏览器信息是的收藏还是取消收藏
    news = models.News.query.get_or_404(news_id)
    if action == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
    db.session.commit()

    return jsonify(errno=RET.OK, errmsg="收藏成功！")


# 评论
@news_blue.route("/news_comment", methods=["POST"])
@check_islogin
def add_news_comment():
    # 获取浏览器参数
    news_id = request.json.get("news_id")
    comment = request.json.get("comment")
    parent_id = request.json.get("parent_id")
    # 获取当前用户
    user = g.user
    # 判断参数是否正确
    if not all([news_id, comment]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))
    # 判断用户是否登录
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map.get(RET.SESSIONERR))

    objComment = models.Comment()
    objComment.user_id = user.id
    objComment.news_id = news_id
    objComment.content = comment
    if parent_id:
        objComment.parent_id = parent_id

    db.session.add(objComment)
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg=error_map.get(RET.OK), data=objComment.to_dict())


# 点赞
@news_blue.route("/comment_like", methods=["POST"])
@check_islogin
def set_comment_like():
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")  # 点赞操作类型：add(点赞)，remove(取消点赞)
    user = g.user

    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map.get(RET.SESSIONERR))

    if action not in ["add", "remove"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))
    #  获取当前评论
    comment = models.Comment.query.get_or_404(comment_id)
    # 获取当前用户是否在当前评论点赞
    comment_like = models.CommentLike.query.filter(models.CommentLike.comment_id == comment_id,
                                                   models.CommentLike.user_id == user.id).first()
    # 判断用户是否点赞
    if action == "add":
        # comment_like = models.CommentLike.query.filter(and_(models.CommentLike.comment_id == comment_id, models.CommentLike.user_id == user.id)).first()
        if not comment_like:
            comment_like = models.CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = user.id
            db.session.add(comment_like)
            comment.like_count +=1
    else:
        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -=1
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")
    return jsonify(errno=RET.OK, errmsg="ok")


# 　关注
@news_blue.route("/followed_user", methods=["POST"])
@check_islogin
def followed_user():
    user = g.user
    user_id = request.json.get("user_id")
    action = request.json.get("action")  # 'follow', 'unfollow'
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg=error_map.get(RET.SESSIONERR))

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    if not action in ["follow", "unfollow"]:
        return jsonify(errno=RET.PARAMERR, errmsg=error_map.get(RET.PARAMERR))

    # 查询关注
    news_user = models.User.query.get(user_id)
    # 要求关注取消关注
    if action == "follow":
        if news_user not in user.followers:
            user.followers.append(news_user)
        else:
            return jsonify(errno = RET.PARAMERR,errmsg = "我已经关注你了")
    else:
        if news_user not in user.followers:
            return jsonify(errno = RET.PARAMERR,errmsg = "没关注")
        else:
            user.followers.remove(news_user)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")
    return jsonify(errno = RET.OK,errmsg = "ok")


